<template>
  <div class="quest-container">
    <div class="flex mb-16">
      <el-button type="primary" @click="addHandle">添加</el-button>
    </div>
    <el-table
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="question" label="题目" />
      <el-table-column fixed="right" label="操作" width="180">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            @click="editHandle(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            size="small"
            @click="delHandle(scope.row)"
            >删除</el-button
          >
          <el-button
            link
            type="primary"
            size="small"
            @click="bindShowHandle(scope.row)"
            >绑定</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="mt-24">
      <Pagination
        class="text-center"
        :page="pageForm.page"
        :limit="pageForm.limit"
        :total="tableTotal"
        @pagination="pageHandle"
      />
    </div>
    <!-- 添加/编辑弹窗 -->
    <el-dialog v-model="show" title="添加/编辑题目" width="700px" align-center>
      <div class="mt-12 dialog-body">
        <el-form
          :model="form"
          ref="formRef"
          label-width="auto"
          style="max-width: 600px"
        >
          <el-form-item
            label="题目"
            prop="question"
            :rules="[
              {
                required: true,
                message: '请输入题目',
                trigger: 'blur'
              }
            ]"
          >
            <el-input v-model="form.question" />
          </el-form-item>
          <el-form-item
            :label="'选项' + (index + 1)"
            v-for="(_, index) in form.options"
            :key="index"
            :props="'options.' + index + '.content'"
            :rules="[
              {
                required: true,
                message: '请输入选项答案',
                trigger: 'blur'
              }
            ]"
          >
            <el-input
              class="flex1 mr-12"
              v-model="form.options[index]['content']"
            />
            <el-button @click="delItems(index)" type="danger" link
              ><el-icon size="16"><DeleteFilled /></el-icon
            ></el-button>
            <el-space wrap>
              <el-form-item
                class="mt-8"
                :label="form.options[index]['attributes'][attrIdx]['name']"
                v-for="(attr, attrIdx) in form.options[index]['attributes']"
                :key="attr.type"
              >
                <el-input
                  style="width: 100px"
                  v-model="form.options[index]['attributes'][attrIdx]['value']"
                />
              </el-form-item>
            </el-space>
          </el-form-item>
          <div class="mb-20 ml-20">
            <el-button
              type="primary"
              @click="addItems"
              :disabled="form.options.length >= 4"
            >
              <el-icon>
                <Plus />
              </el-icon>
              <span class="ml-6">添加选项</span></el-button
            >
          </div>
          <el-form-item label="提示">
            <el-input v-model="form.tips" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="show = false">取消</el-button>
          <el-button type="primary" @click="formSubmit"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 绑定站点弹窗 -->
    <el-dialog v-model="bindShow" title="绑定站点" width="700px" align-center>
      <div class="mt-12 dialog-body">
        <el-form :model="bindForm" label-width="auto" style="max-width: 600px">
          <el-form-item label="站点" prop="locations">
            <el-select
              v-model="bindForm.locations"
              multiple
              placeholder="请选择站点"
              class="w100"
            >
              <el-option
                v-for="item in siteOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="bindShow = false">取消</el-button>
          <el-button type="primary" @click="bindSubmit"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import Pagination from '@/components/Pagination';
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  apiQuestionList,
  apiQuestionDel,
  apiQuestionAdd,
  apiQuestionEdit,
  apiBindLocations
} from '@/api/question';
import { apiLocationAll } from '@/api/site';
const tableData = ref([]);
const tableTotal = ref(0);
const show = ref(false);
const initalValues = {
  question: '',
  options: [],
  tips: ''
};
const form = ref(initalValues);
const formRef = ref(null);
// 添加内容字段
const addItems = () => {
  form.value.options.push({
    content: '',
    attributes: [
      {
        type: 1,
        name: '学',
        value: 0
      },
      {
        type: 2,
        name: '艺',
        value: 0
      },
      {
        type: 3,
        name: '商',
        value: 0
      },
      {
        type: 4,
        name: '医',
        value: 0
      },
      {
        type: 5,
        name: '武',
        value: 0
      }
    ]
  });
};
// 删除内容字段
const delItems = (index) => {
  form.value.options.splice(index, 1);
};
// 删除
const delHandle = ({ id }) => {
  ElMessageBox.confirm('您确定要删除这个问题吗?', '删除提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      apiQuestionDel({
        id
      }).then((res) => {
        if (res.code === 200) {
          ElMessage({
            type: 'success',
            message: '删除成功'
          });
          getData();
        }
      });
    })
    .catch(() => {});
};
/**
 * 编辑
 */
const editId = ref('');
const editHandle = (record) => {
  show.value = true;
  formRef.value?.resetFields();
  editId.value = record.id;
  form.value = JSON.parse(JSON.stringify(record));
};
// 添加
const addHandle = () => {
  show.value = true;
  formRef.value?.resetFields();
  editId.value = '';
  form.value = initalValues;
};
/**
 * 表单保存
 */
const formSubmit = async () => {
  await formRef.value.validate(async (valid) => {
    if (valid) {
      const api = editId.value ? apiQuestionEdit : apiQuestionAdd;
      const params = editId.value
        ? { ...form.value, id: editId.value }
        : form.value;
      const { code } = await api(params);
      if (code === 200) {
        ElMessage({
          type: 'success',
          message: '保存成功'
        });
        show.value = false;
        getData();
      }
    }
  });
};
/**
 * 表格勾选复选框
 */
const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
  console.log(val);
};
/**
 * 分页
 */
const pageForm = ref({
  page: 1,
  limit: 10
});
const pageHandle = (val) => {
  pageForm.value = val;
  getData();
};
// 获取表格数据
const getData = async () => {
  const { data, total } = await apiQuestionList(pageForm.value);
  tableData.value = data;
  tableTotal.value = total;
};
onMounted(() => {
  getData();
});
/**
 * 绑定站点
 */
const bindForm = ref({});
const bindShow = ref(false);
const bindShowHandle = ({ id, locations }) => {
  editId.value = id;
  bindShow.value = true;
  bindForm.value.locations = locations;
};
const bindSubmit = async () => {
  const { code } = await apiBindLocations({
    id: editId.value,
    locations: bindForm.value.locations
  });
  if (code === 200) {
    ElMessage.success('绑定成功');
    bindShow.value = false;
    getData();
  }
};
const siteOptions = ref([]);
const getSiteOptions = async () => {
  const { data } = await apiLocationAll();
  siteOptions.value = data;
};
onMounted(() => {
  getSiteOptions();
});
</script>

<style scoped>
.quest-container {
  position: relative;
  width: 100%;
  height: calc(100vh - 84px);
  padding: 16px;
  box-sizing: border-box;
}
.dialog-body {
  max-height: 70vh;
  overflow: auto;
}
</style>
